export default class Camera {
    constructor() {}
    target!: Laya.Sprite;
    lastTarget: [number, number] = [0, 0];
    private _stage: Laya.Sprite = Laya.stage;
    get stage() {
        return this._stage || Laya.stage;
    }
    set stage(value) {
        this._stage = value;
    }
    /** 解除摄像机跟随舞台 */
    clearStage() {
        this.stopTrack();
        this.setStage(Laya.stage);
    }
    /** 设置摄像机跟随的舞台 */
    setStage(sprite: Laya.Sprite) {
        Laya.Physics.I.worldRoot = sprite;
        // this.checkDebugger();
        this.stage = sprite;
    }
    /** 修正在摄像机下物理错位*/
    checkDebugger(scrollRect: Laya.Rectangle) {
        if ((Laya.PhysicsDebugDraw as any)._inited) {
            Laya.PhysicsDebugDraw.I.scrollRect = scrollRect;
        }
    }
    /** 摄像机追踪一个 Sprite */
    tracking(sprite: Laya.Sprite) {
        this.target = sprite;
        Laya.timer.frameLoop(1, this, this._TrackLooper);
    }
    _TrackLooper() {
        if (this.target) {
            const position: [number, number] = [this.target.x, this.target.y];
            if (
                this.lastTarget[0] !== position[0] ||
                this.lastTarget[1] !== position[1]
            ) {
                this._move(this.target.x, this.target.y);
                this.lastTarget = position;
            }
        }
    }
    stopTrack() {
        console.log("摄像机: 停止跟踪");
        Laya.timer.clear(this, this._TrackLooper);
    }
    private _move(x: number, y: number) {
        // 每次重建正方形保证 stage 变化时仍然可以适应
        const rect = new Laya.Rectangle(
            x - Laya.stage.width / 2,
            y - Laya.stage.height / 2,
            Laya.stage.width,
            Laya.stage.height
        );
        this.stage.scrollRect = rect;
        this.checkDebugger(rect);
    }
    /** 摄像机跳跃到一个物体上 */
    moveTo(x: number, y: number) {
        this.stopTrack();
        this._move(x, y);
    }

    /** 判断一个物体是否在摄像机内 */
    isInCamera(target: Laya.Sprite, extraRange: number = 0) {
        const { x, y } = target;
        const w = Laya.stage.width / 2 + extraRange;
        const h = Laya.stage.height / 2 + extraRange;
        let [x1, y1] = this.lastTarget;
        if (x > x1 - w && x < x1 + w) {
            if (y > y1 - h && y < y1 + h) {
                return true;
            }
        }
        return false;
    }
}
